package service

import (
	"context"
	log "github.com/micro/go-micro/v2/logger"
	"rpc-service/product/model"
	"rpc-service/product/proto/product"
	"rpc-service/product/repository"
)

type ProductService struct {
	CommonService
}

/**
 * 获取列表
 */
func (s *ProductService) GetProductList(ctx context.Context, req *product.ProdRequest, resp *product.ProdListResponse) error {
	log.Info("GetProdList,request:", req.Size)
	if products, err := repository.GetInstance().FindListLimit(req.Size); err != nil {
		log.Error("GetProductList Error", err)
		//错误信息传给调用方
		resp.Code = s.FailedMessage(5001, "查询商品列表失败", err.Error())
		return err
	} else {
		prods := make([]*product.Product, 0)
		var i int
		for i = 0; i < len(products); i++ {
			prods = append(prods, &product.Product{ProdId: int32(products[i].ID), ProdName: products[i].Name})
		}
		resp.Data = prods
	}
	return nil
}

/**
 * 获取详情
 */
func (s *ProductService) GetProductDetail(ctx context.Context, req *product.Product, resp *product.ProductResponse) error {
	log.Info("GetProdDetail..", req)
	//prod :=  &model.Product{ID: uint(req.ProdId), Name: req.ProdName}
	if prod, err := repository.GetInstance().Find(uint32(req.ProdId)); err != nil {
		resp.Code = s.FailedMessage(5002, "获取商品详情失败", err.Error())
		return err
	} else {
		resp.Data = &product.Product{ProdId: int32(prod.ID), ProdName: prod.Name}
		return nil
	}
}

/**
 * 创建商品
 */
func (s *ProductService) CreateProduct(ctx context.Context, req *product.Product, resp *product.ProductResponse) error {

	log.Info("CreateProduct..", req)
	newProd := model.Product{Name: req.ProdName}
	if err := repository.GetInstance().Create(&newProd); err != nil {
		resp.Code = s.FailedMessage(5003, "创建商品失败", err.Error())
		return err
	}
	return nil
}

/**
 * 更新商品
 */
func (s *ProductService) UpdateProduct(ctx context.Context, req *product.Product, resp *product.ProductResponse) error {

	log.Info("CreateProduct..", req)
	newProd := &model.Product{ID: uint(req.ProdId), Name: req.ProdName}
	if prod, err := repository.GetInstance().Update(newProd); err != nil {
		resp.Code = s.FailedMessage(5004, "更新商品失败", err.Error())
		return err
	} else {
		resp.Data = &product.Product{ProdId: int32(prod.ID), ProdName: prod.Name}
		return nil
	}
}

/**
 * 删除商品
 */
func (s *ProductService) DeleteProduct(ctx context.Context, req *product.Product, resp *product.ProductResponse) error {

	log.Info("DeleteProduct..", req)
	delProd := &model.Product{ID: uint(req.ProdId), Name: req.ProdName}
	if prod, err := repository.GetInstance().Delete(delProd); err != nil {
		resp.Code = s.FailedMessage(5005, "删除商品失败", err.Error())
		return err
	} else {
		resp.Data = &product.Product{ProdId: int32(prod.ID), ProdName: prod.Name}
		return nil
	}
}
